package com.xplay.xpocker.room.message.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.xplay.xpocker.constant.RoomTypeEnum;
import com.xplay.xpocker.entity.GameRuRoom;
import com.xplay.xpocker.room.message.AbstractActionStrategy;
import com.xplay.xpocker.room.message.MessageContent;
import com.xplay.xpocker.room.message.AbstractMessageStrategy;
import com.xplay.xpocker.util.Assertion;
import com.xplay.xpocker.util.JacksonStringUtil;
import com.xplay.xpocker.util.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import com.xplay.xpocker.service.gaming.GameRuRoomService;
import com.xplay.xpocker.room.message.MessageType;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ActionMessageService extends AbstractMessageStrategy {
    @Resource
    private GameRuRoomService gameRuRoomService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doMessage(String code, MessageContent<Object> data) {
        GameRuRoom gameRuRoom = gameRuRoomService.queryRoomByCode(code);
        // 获取房间是那种类型
        int roomTypeParent = RoomTypeEnum.of(gameRuRoom.getType()).getParent();
        AbstractActionStrategy<?, ?> actionStrategy = AbstractActionStrategy.ROOM_TYPE_ACTION_STRATEGY.get(roomTypeParent);
        Assertion.isNull(actionStrategy, "消息有误");
        String bodyStr = JacksonStringUtil.objectToString(data.getBody(), false);
        List<Map<String, Object>> mapList = JacksonStringUtil.objectCase(bodyStr, new TypeReference<List<Map<String, Object>>>() {});
        if (ObjectUtils.notEmpty(mapList)) {
            for (Map<String, Object> param : mapList) {
                actionStrategy.message(gameRuRoom, param);
            }
        } else {
            Map<String, Object> param = JacksonStringUtil.objectCase(bodyStr, new TypeReference<Map<String, Object>>() { });
            actionStrategy.message(gameRuRoom, param);
        }
    }

    @Override
    protected int strategyName() {
        return MessageType.ACTION.getType();
    }
}
